<?php

namespace App\Jobs;

use App\Lib\WeApp\WeApp;
use App\Wen\Utils\GatewayUtils;
use App\Wen\Utils\Settings;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class TempleteMessageJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $data;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        global $__MINI_GLOBAL_PAYCODE_2__;
        if(!$__MINI_GLOBAL_PAYCODE_2__){
            return null;
        }
        $weapp = new WeApp('mp');
        if(is_string($this->data)){
            $this->data = json_decode($this->data, true);
        }
        $templateMsg = $weapp->getTemplateMsg();
        try{
            $pagepath = '';
            if(isset($this->data['miniprogram']) && is_array($this->data['miniprogram']) && $this->data['miniprogram']['pagepath']){
                $pagepath = $this->data['miniprogram']['pagepath'];
            }
            $res = $templateMsg->send($this->data['touser'],$this->data['template_id'],$this->data['data'], $pagepath, _array_key($this->data, 'url', ''));
        }catch (\Exception $e){
            if(strpos($e->getMessage(), '40013:invalid appid') === 0){
                _logger_(__file__, __line__, '检查三个地方：1、你的公众号appid和appsecret是否配置正确，2、你的公众号是否关联了小程序 3、如果这个提示一直存在，超过3日，想不到原因了...');
            }else{
                _logger_(__file__, __line__, $e->getMessage());
            }
        }

    }
}
